package uppacket

import (
	"time"

	"gitee.com/yanwc/ebike-xiaoan-device/device"
	"gitee.com/yanwc/ebike-xiaoan-device/device/config"
	"gitee.com/yanwc/ebike-xiaoan-device/internal/codec"
	"gitee.com/yanwc/ebike-xiaoan-device/internal/field"
	"gitee.com/yanwc/ebike-xiaoan-device/internal/frame"
	"gitee.com/yanwc/net/utils"

	"github.com/panjf2000/gnet"
)

type HeartBeatPacket struct{}

var _ IUpPacket = (*HeartBeatPacket)(nil)

func (hbp *HeartBeatPacket) Do(frame frame.IFrame, c gnet.Conn) ([]byte, gnet.Action, error) {
	var csqRaw field.CSQRaw

	var voltage field.VoltageVRaw
	utils.LoadPacket(frame.Content(), csqRaw[:], voltage[:])
	// 更新设备心跳信息
	if d, ok := device.SessionDevices.GetWithConn(c); ok {
		d.LastUpdatedAt = time.Now()
		if d.OnHeartBeatNotify != nil {
			csq, err := csqRaw.Type()
			if err != nil {
				return nil, gnet.None, err
			}

			go d.OnHeartBeatNotify(config.Context{}, csq, voltage.Type())
		}
	} else {
		return nil, gnet.Shutdown, nil
	}

	f := &codec.Frame{
		Header: &codec.Header{
			CmdWord: field.CommandWord(0x02),
			SN:      frame.GetSN(),
		},
	}

	return f.WrapPacket(nil), gnet.None, nil
}
